/**
 * tjftp -- A simple FTP server, using the ANSI C
 * Copyright (C) 2011  degui.chen <degui.chen@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "dispatcher.h"
#include "lib/unity.h"
#include <errno.h>

int tj_dispatch_client(int accept_fd) {
	//读取请求信息
	char request_buf[1024] = { '\0' };
	int recv_leng = tj_epoll_receive(accept_fd, request_buf, 1024);
	if (-1 == recv_leng) {
		return -1; //客户端发起重新连接
	}
	if (0 == recv_leng) {
		return 0;
	}
	DEBUG_LOG("通知用户发送信息", 0);
	tj_plugin_receive(request_buf);
	char temp[1024] = { '\0' };
	sprintf(temp, "recv message '%s'", request_buf);
	printf("---------------------------------------------------------------- \n");
	printf("client send %s \n", request_buf);
	DEBUG_LOG(temp, 1);
	//处理请求，并返回结果
	DEBUG_LOG("在这里使用命令模式，来实现多态，处理用户请求。", 0);
	char response_buf[1024] = { '\0' };
	int res_len = tj_command_exec(accept_fd, request_buf, response_buf);
	//发送响应信息
	DEBUG_LOG("通知回复请求用户信息", 0);
	tj_plugin_send(response_buf);
	if (res_len < 0) {
		memset(response_buf, '\0', 1024);
		sprintf(response_buf, "未知命令 '%s' .", request_buf);
	}
	send(accept_fd, response_buf, strlen(response_buf) + 1, 0);
	sprintf(temp, "send message %s ", response_buf);
	DEBUG_LOG(temp, 1);
	//tj_sesstion_dump(accept_fd);
	return 0;
}
